import { snakeCase, includes, isString } from 'lodash'
import { Notification } from 'element-ui'

function timePeriodArrToStr(timePeriods) {
  const timeArr = []
  timePeriods.forEach(function (i) {
    const timeStr = i.time[0] + '-' + i.time[1]
    if (i.time[0] && i.time[1] && !includes(timeArr, timeStr)) {
      timeArr.push(timeStr)
    }
  })
  return timeArr.join(';')
}

function errorNotify(err) {
  let desc = '未知错误'
  if (err instanceof Error) {
    if (err.response) {
      const { status, data } = err.response
      const { user_message: userMessage, message } = data
      if (userMessage || message) {
        // 正常报错
        desc = userMessage || message
      } else {
        // 异常报错(服务端挂了)
        if (status >= 400 && status < 500) {
          desc = `[${status}] 请求错误`
        } else {
          desc = `[${status}] ${data}`
        }
      }
    } else if (err.request) {
      desc = '请求无响应'
    } else {
      desc = err.message
    }
    // description = `[${err.code}] ${err.message}`;
  } else if (isString(err)) {
    desc = err
  }

  Notification.error({
    title: '错误！',
    message: desc
  })
}

function successNotify(message = '') {
  Notification.success({
    title: '成功',
    type: 'success',
    message
  })
}

/**
 * 将数据以querystring的方式存放在route中
 * @param {string} name - 参数名
 * @param config
 * @param {any} config.default - 参数的默认值
 * @returns {{}|*}
 */
function storeToRouteQuery(name, config) {
  return {
    [name]: {
      get() {
        const snakeCaseName = snakeCase(name)
        if (this.$route.query[snakeCaseName]) {
          return this.$route.query[snakeCaseName]
        }
        return config.default
      },
      set(val) {
        const snakeCaseName = snakeCase(name)
        this.$router.replace({
          name: this.$route.name,
          params: this.$route.params,
          query: {
            ...this.$route.query,
            [snakeCaseName]: val
          }
        })
      }
    }
  }
}

/**
 * 对async函数做cache
 * 用于减少不必要网络请求
 * 注意func理论上应该是一个不能接受任何参数的async函数（普通函数意义不大）
 */
export function asyncFuncCacheWrapper(func) {
  let cached = false
  let value

  return async function () {
    if (cached) {
      return value
    }
    value = await func()
    // eslint-disable-next-line require-atomic-updates
    cached = true
    return value
  }
}

/**
 * 转换为科学计数法
 */
export function numFormat(value) {
  if (value !== undefined) {
    return value.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
  } else {
    return 0
  }
}

export function setUrlParams(_this, key, value) {
  const obj = JSON.parse(JSON.stringify(_this.$router.currentRoute.query))
  obj[key] = value
  _this.$router.push({ query: obj })
}

export function deleteUrlParams(_this, key) {
  const obj = JSON.parse(JSON.stringify(_this.$router.currentRoute.query))
  delete obj[key]
  _this.$router.push({ query: obj })
}

export { timePeriodArrToStr, successNotify, errorNotify, storeToRouteQuery }
